<?php
namespace App\Api;

use Illuminate\Support\Facades\Log;
use SF\libaray\curl;

class request
{
    // 请求句柄
    protected $request;

    public function __construct()
    {
        $this->request = new curl();    //curl
    }

    /**
     * 请求服务封装
     * @param string $service 请求服务名
     * @param array $param  请求参数
     * @param boolean $debug 调试模式
     * @return void
     */
    public function send( $service, $param = array(), $debug = false )
    {
        //读取配置
        $config = config( 'user.server' );

        // 参数ascii码排序
        ksort( $param );

        // 初始化时间戳
        $timestamp = microtime();

        //初始发送化数据
        $data = [
            'appKey' => $config[ 'app_key' ],
            'content' => $param,
            'timestamp' => $timestamp,
            'version' => $config[ 'version' ]
        ];

        $signature = md5( 'appKey=' . $data[ 'appKey' ] . '&content=' . $data[ 'content' ] . '&timestamp=' . $timestamp . '&version=' . $data[ 'version' ] . $config[ 'app_secret' ] );    // 签名
        $data[ 'sign' ] = $signature;

        //开始请求接口
        if( $response = $this->request->post( $config[ 'api' ], $data ) )
        {
            dd( $response );
            //调试模式
            if( $debug )
            {
                dd( [ 'param' => $param, 'data' => $data, 'response' => $response ] );
            }

            if( $response = json_decode( $response, true ) )
            {
                return $response;
            }
        }
        
        //记录日志
        Log::error( json_encode( array( 'param' => $param, 'data' => $data, 'response' => $response ) ), 'error' );
        return false;
    }
}